var socketio = require('socket.io');
var cusers=[];
var DaoMysql= require('./models/dao-mysql').DaoMysql,
CacheRedis  = require('./models/cache-redis').CacheRedis,
User        = require('./models/user').User;
var dao;
exports.create = function(app,port){
	dao = new DaoMysql(app.envConfig.dbMysql, app.mysqlClient, app.logmessage, new CacheRedis(app.envConfig.storeRedis, app.redisClient, app.logmessage, app.defs.DEFAULT_CACHE_EXPIRE_SECS));
	return socketio.listen(port).on('connection', function (socket) {
		//下线
		socket.on('disconnect',function(reason){
		   upOrdown(false,cusers[socket.id].user);
		   updateUserOnline(cusers[socket.id].user.id,0);
		   delete cusers[socket.id];
		});
		socket.on('message',function (msg) {
			onMessage(socket,msg);
		});
	});
};

//上下线处理
function upOrdown(isup,user){
	var msg={};
	if(isup){
		msg.type="online";
	}else{
		msg.type="offline";
	}
	msg.msg=user;
	var jmsg=JSON.stringify(msg);
	for(var key in cusers){
		cusers[key].sokect.send(jmsg);
	}
	console.log(msg.type+":"+jmsg);
}
function pushOnlineAll(sokect){
	var msg={};
	msg.type="allonline";
	msg.msg=new Array();
	for(var key in cusers){
		msg.msg.push(cusers[key].user);
	}
	var s=JSON.stringify(msg);
	sokect.send(s);
	console.log(msg.type+":"+s);
}

function onMessage(socket,json){
    jsonObject = JSON.parse(json);
    var type = jsonObject.type;
    switch (type){
        case 'login':
        	pushOnlineAll(socket);
        	upOrdown(true,jsonObject.msg);
			var us={};
	   		us.sokect=socket;
	   		us.user=jsonObject.msg;
	   		cusers[socket.id]=us;
	   		updateUserOnline(us.user.id,1);
            break;
        case 'msg':
            break;
    }
};

function updateUserOnline(id,online){
	if(id){
		dao.get(User,id, function(err,result){
			if(err){
				console.log(err);
			}else{
				result.online=online;
				dao.update(new User(result),function(err,result){
	        		console.log(result);
	        	});
			};
		});
	}
}
